import { Component, OnInit, Inject,ElementRef,ViewChild } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import {UtilityService} from '../../../../service/utils.service';
import {appConfig} from '../../../../service/common';
import {NzModalService, NzNotificationService,NzMessageService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { WorkitemModule } from '../../../../service/delivent/workItemModule';
import { BranchModule} from '../../../../service/delivent/brachModule';
import * as _ from 'lodash';
import * as moment from 'moment';
import {ProductModule} from '../../../../service/delivent/projectModule';

@Component({
  selector: 'app-s-workitem',
  templateUrl: './s-workitem.component.html',
})
export class SWorkitemComponent implements OnInit {


    constructor(
        private http: _HttpClient,
        private router: Router,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
        private _message: NzMessageService,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    ) { }

 @ViewChild('input') private input: ElementRef;
    // 变量
    isPagination = true; // 是否有分页
    showAdd: boolean; // 是否有修改
    workItem: WorkitemModule = new  WorkitemModule(); // 信息
    workAdd: WorkitemModule = new  WorkitemModule(); // 信息
    data: any[] = []; // 表格数据
    modalVisible = false; // 默认弹出框关闭
    assVisible = false; // 默认关闭
    modelTitle: string; // 默认名称
    isUpd = false;
    expandForm = false;
    headerDate = [  // 配置表头内容
        { value: 'itemNamestr', label: '工作项名称', key: 'itemNamestr', isclick: true, title: true },
        { value: 'developers',  label: '开发人员', key: 'developers', isclick: false },
        { value: 'owner',  label: '工作项负责人', key: 'owner', isclick: false },
        { value: 'developStartTime',  label: '启动开发时间', key: 'developStartTime', isclick: false },
        { value: 'deliveryPlanTime',  label: '计划投产时间', key: 'deliveryPlanTime', isclick: false },
        { value: 'itemStatus',  label: '工作项状态', key: 'itemStatus', isclick: false },
        { value: 'itemLablesWork',  label: '工作项标签', key: 'itemLablesWork', isclick: false },
        { value: 'workType',  label: '工作项类型', key: 'workType', isclick: false },
    ];
    checkOptionsOne = [
        { label: '新建分支', value: 'branch', checked: true },
        { label: '新建工程', value: 'project', checked: false },
    ];
     AddTabs = [
            { name   : '基础信息', content:0 },
            { name   : '需求信息', content: 1 },
            { name   : '工作量&进度', content: 2 },
            { name   : '收款管理', content: 3  },
            { name   : 'PM管理备注', content:4 }
  ];
  SelectedIndex = 0
    projectInfo = false;
    prolist: any[] = []; // 工程列表
    // 传入按钮层
    moreData = {
        morebutton: true,
        buttonData: [
        ]
    }
    pageIndex=1;
    expand = false;
    tabs = [
        {active: true, name  : '选择已有分支'},
        {active: false, name  : '新增分支'}];
    test: string;
    page: any;
    token: any; // token
    total: number;
    pageTotal: number;
    buttons = [
        {key: 'add', value: '新建工作项', if: true}
    ];
    assbranch: any; // 分支信息
    exitInfo: any;
    isEdit = false; // 默认是新增
    isShowTotal: boolean;
    subPro = []
    branchInfo = false; // 弹出框 默认为false
    branchData: BranchModule = new BranchModule();
    branchdataInfo: boolean; // 分支详情
    _isSpinning = true;
    // 枚举值
    owner: any; // 人员
    branch = []; // 查询分支
    branchType = [
        {key: 'feature', value: 'F', selector:false},
        {key: 'hotfix', value: 'H' , selector:false},
    ]
     addBranch = {
        branchType: null,
        branchFor: null
    };
    workType =[
          {label: '需求', value: 'D', selector:false},
          {label: '项目', value: 'P', selector:false},
         {label: '生产事件', value: 'E', selector:false}
    ]
    itemStatus = [
          {label: '开发中', value: '0', selector:false},
          {label: '已投产', value: '1', selector:false},
         {label: '已取消', value: '2', selector:false}
    ]
     workGroup = [
        {label: '运维组', value: '0'},
        {label: '应用一组', value: '1'},
        {label: '应用二组', value: '2'},
        {label: '应用三组', value: '3'},
        {label: '应用四组', value: '4'},
        {label: 'pad组', value: '5'}

    ]
        workSource = [
        {label: '新柜面', value: 'N'},
        {label: '老柜面', value: 'O'},
        {label: 'pad', value: 'P'}
    ]
      proceedsStatus = [
        {label: '未收款', value: '0'},
        {label: '已收款', value: '1'}
    ]
    attentionType = [
         {label: '暂缓开发', value: '0'},
         {label: '需求不明确', value: '1'},
         {label: '部分收款内容', value: '2'},
    ]
    searchFun = {
        itemName:null,
        owner:null,
        itemLable:null,
        itemStatus:null,
        deliveryPlanTime:null
    }
    searchtags:string;
    active = true;
    list = [];
    searchRevert = null;
    tag = '验证'
    revertListModal = false;
    revertListData = []
    revertSelectedRows = [];
    revertListHeaderDate =  [  // 配置表头内容
       { label: '序号', value: 'index', isclick: false },
        { label: '代码', value: 'fullPath', isclick: false }
    ];

    // 初始化方法
    ngOnInit() {
        this.showAdd = true;
        this.isShowTotal = true;
        this.branchdataInfo = false; // 默认不显示详情
        this.token  = this.tokenService.get().seniortoken; // 绑定token
        this.getData();
        this.getOper()
        this.initDate(); // 默认时间
    }
    isShowTotalhead = true;
    listloading = false;
    getData(option?) {
        if (option) {
           this.pageIndex =1;
        }


         this.page = {

                condition: this.searchFun, // 搜索内容

                page: {
                    current: this.pageIndex,
                    size: 10,
                    orderByField: 'guid',
                    asc: false // asc 默认是true  升序排序，时间类型 用false， 降序
                }
            };
       this.listloading = true;
        this.utilityService.postData(appConfig.testUrl  + appConfig.API.workItemList , this.page )
            .subscribe(
                (val) => {
                    this.listloading = false;
                    this.data = val.result.records;
                    this.total = val.result.total;
                    this.pageTotal = val.result.pages * 10;

                   this.data.forEach(value=> {

                                 value.itemNamestr = value.itemName
                                 value.itemLable = value.itemLables
                                 value.itemLablesWork = value.itemLables;
                                if (value.itemName.length > 20) {
                                value.itemNamestr = appConfig.subString(value.itemName, 10);
                            }

                        if (value.itemStatus === '开发中') {

                             if(this.tokenService.get().role === '开发组') {
                                  this.isShowTotal = false
                                value.buttonData = [
                                     {key: 'revert', value: '回退代码'},
                                    //  {key: 'delay', value: '延期申请'}
                                         ];
                               }else{
                                   if (value.fullPath !== '') { // 说明存在分支
                                value.buttonData = [
                                     {key: 'close', value: '取消分支'},
                                     {key: 'revert', value: '回退代码'},
                                    //  {key: 'delay', value: '延期申请'},
                                     {key: 'branchDDetail', value: '分支详情'},
                                    {key: 'upd', value: '修改'},
                                    {key: 'cenel', value: '关闭'},
                                    {key: 'project', value: '拉工程'},
                                    {key: 'putProductStatus', value: '已投产'},

                                ];
                            } else {

                                    value.buttonData = [
                                    {key: 'association', value: '关联分支'},
                                    {key: 'revert', value: '回退代码'},
                                    // {key: 'delay', value: '延期申请'},
                                    {key: 'upd', value: '修改'},
                                    {key: 'cenel', value: '关闭'}


                                ];


                            }
                             }

                        }


                        value.receiveTime = moment(value.receiveTime).format('YYYY-MM-DD');
                        value.developStartTime = moment(value.developStartTime).format('YYYY-MM-DD');
                        value.deliveryTime = moment(value.deliveryTime).format('YYYY-MM-DD');
                        value.deliveryPlanTime = moment(value.deliveryPlanTime).format('YYYY-MM-DD');
                    });
                 console.log(this.data)

                },
                (error) => {
                        this.listloading = false;
                    this.nznot.create('error', error.code , error.msg);
                }
            );
    }
    // 查询方法
    search() {
        this.getData(this.workItem);
    }
    // 获取标签

    // 重置方法
    reset() {
        this.searchFun = {
        itemName:null,
        owner:null,
        itemLable:null,
        itemStatus:null,
        deliveryPlanTime:null
    }
        this.getData();
    }
    // 查询分支
    getBranch() {
        this.utilityService.getData(appConfig.testUrl  + appConfig.API.notAllot)
            .subscribe(
                (val) => {
                 this.branch = val.result;

            });
    }
    // 查询人员
    getOper() {
        this.utilityService.postData(appConfig.testUrl  + appConfig.API.svncount , {} )
            .subscribe(
                (val) => {
                    console.log(val)
                    this.owner = val.result;
                });
    }

    // 初始化时间
    initDate() {
        this.workAdd.receiveTime =  moment(new Date()).format('YYYY-MM-DD');
        this.workAdd.developStartTime =  moment(new Date()).format('YYYY-MM-DD');
        this.workAdd.deliveryTime =  moment(new Date()).format('YYYY-MM-DD');
        this.workAdd.deliveryPlanTime =  moment(new Date()).format('YYYY-MM-DD');
    }
    // 新增方法
    addHandler(event) {
        if (event === 'add') {
            this.workAdd = new WorkitemModule(); // 清空
            this.strdevelopers = null;
             this.checkType = 'A'; // 修改
            this.isShowArtf = false;
              this.SelectedIndex = 0;
            this.modalVisible = true;

            this.isEdit = false;
            this.modelTitle = '新建工作项';
        }
    }
    tags = [];
    checkTabs(event){
     console.log(event)
     setTimeout(()=>{

        this.utilityService.postData(appConfig.testUrl  +'/sWorkitem/lable' , {lableName:event} )
            .subscribe(
                (val) => {
                    this.tags = val.result

               },(error)=>{
            this.nznot.create('error', error.code , error.msg);
            });


    },300);
}

 isShowworkload = false;
 workload:string;
  checkworkload(event){
        console.log(event)
      if(event!=''){
            let MOBILE_REGEXP =/^\+?[1-9][0-9]*$/;

        if (MOBILE_REGEXP.test(event) === true ) {
            this.isShowworkload = false
        }else {
            this.isShowworkload = true;
              this.workload = '只能输入整数'
        }
      }else{
            this.isShowworkload = false
      }

  }

    // 工作项名称跳转工作项详情界面
    isActive(event)  {

        this.router.navigate(['workView'],
            { queryParams:
                    { workGuid: event.guid  }
            });
    }
    buttonDataHandler(event) {

    }

isShowitemName = false;
isShowseqno = false;
isShowrequirementDesc  = false
    checkString(event,it){

        var regs=/['\,]+/g;

       if(regs.test(event)){

         switch(it){
             case 1:
             this.isShowitemName = true;
             break;
              case 2:
             this.isShowseqno = true;
             break;
             default:
              this.isShowrequirementDesc = true;
             break;

         }

      }else{

            switch(it){
             case 1:
             this.isShowitemName = false;
             break;
              case 2:
             this.isShowseqno = false;
             break;
             default:
              this.isShowrequirementDesc = false;
             break;

         }
      }
      console.log(it)



    }

    // 翻页方法
    monitorHandler(event) {
        this.pageIndex = event;
         this.getData();
    }

      filterOption(inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
      }

      searchpro(ret: any) {
      }

      select(ret: any) {
      }

      change(ret: any) {
         for (let i = 0 ; i < ret.list.length; i++){
             ret.list[i]['status'] =  ret.to
         }
      }

     onSearch(it){
         this.searchRevert = it;
         this.getRevert(it)
      console.log(it)
     }
    tabChange(obj) {
        this.active = obj;
    }

    workId: string; // 工作项ID
    // 按钮点击事件方法
    checkType:string;
    onClose(it){

    }
    Upddevelopers:any[]=[];
    selectVisible = false
    showselect(){
      this.strdevelopers = null
      console.log( this.strdevelopers)
    // setTimeout(() => {
    //     this.input.nativeElement.focus();
    // }, 10);

  }

    strdevelopers:any
    Adddevelopers(it){

      for(let i = 0;i<  this.workAdd.developersAdd.length;i++){
              if(this.workAdd.developersAdd[i].userId===it){
                return;
              }
        }
           this.owner.forEach(i=>{
                         if(i.userId===it){
                              this.workAdd.developersAdd.push(i);
                         }

                  })

    }
    revertpage:any;
    revertPageIndex = 1
    isrevertPagination = true;
    revertpageTotal:number;
    isCaocuo = false;
    reason = null;
    delaysSeclect = [];
    getRevert(option?){
          if (option) {
           this.revertPageIndex =1;
        }

          this.revertpage = {
                condition: {fullPath:this.searchRevert}, // 搜索内容
                page: {
                    current: this.revertPageIndex,
                    size: 10,
                    orderByField: 'guid',
                    asc: false // asc 默认是true  升序排序，时间类型 用false， 降序
                }
            };
        this.listloading = true;
        this.utilityService.postData(appConfig.testUrl  + '/sWorkitem/'+this.workId+'/standardListAll' , this.revertpage )
                           .subscribe(
                                (val) => {

                                  this.listloading = false;
                                  val.result.records.forEach((i,index)=>{
                                      val.result.records[index]['index'] = index+1;
                                      i.checked = false;
                                      this.delaysSeclect.forEach(j=>{
                                          if(i.guid === j){
                                              i.checked = true;
                                          }
                                      })
                                  });
                                     console.log(val)
                                  this.revertListData = val.result.records
                                  this.revertpageTotal = val.result.pages * 10;

                                  this.revertListModal = true

                                },(error) =>{
                                      this.listloading = false;
                                    this.nznot.create('error', error.code , error.msg);
                                }
                            );
    }
    revertMonitorHandler(event){
        this.revertPageIndex = event;
        this.getRevert();
    }

    selectedRowslist = 0;
    buttonEvent(event) {
        this.workId = event.guid;
        if (!_.isNull(event.names)) {
            if (event.names.key === 'upd') {
                this.checkType = 'U'; // 修改
                this.strdevelopers = null;
                this.modelTitle = '修改工程';
                this.modalVisible = true;
                this.workAdd = _.cloneDeep(event);
                this.isShowArtf = false
                this.workType.forEach(i=>{
                    if(i.label === this.workAdd.workType){
                      this.workAdd.workType = i.value
                    }
                })
                  this.workAdd.developersAdd = []
                let obj = this.workAdd.developers.split(',')
                  this.owner.forEach(i=>{
                     obj.forEach(j=>{
                         if(i.userId===j){
                             this.workAdd.developersAdd.push(i)
                         }
                     })
                  })
                this.workAdd.itemLable = event.itemLable;
                this.isEdit = true;
            } else if(event.names.key === 'project') {
                   this.utilityService.getData(appConfig.testUrl  + appConfig.API.sWorkitem + '/' +  event.guid + '/project')
                            .subscribe(
                                (val) => {
                               let others = [];
                               let own = []
                                   if (val.result.others.length > 0) {
                                        for (let j = 0; j < val.result.others.length; j++){
                                          val.result.others[j]['exit'] = 'left';
                                   }
                                }
                                  if (val.result.own.length > 0) {
                                       for(let j = 0; j < val.result.own.length; j++) {
                                              val.result.own[j]['exit'] = 'right';
                                       }
                                    }
                                    others = val.result.others;
                                    own = val.result.own;
                                    if (own.length > 0 && others.length > 0) {
                                           others = others.concat(own);
                                    }else if (others.length === 0 && own.length > 0 ) {
                                         others = own;
                                    }
                               const ret = [];
                                for (let i = 0; i < others.length; i++) {

                                ret.push({
                                    key: i.toString(),
                                    title: others[i]['projectName'],
                                    guid: others[i]['guid'],
                                    status: others[i]['exit'],
                                    description: others[i]['projectName'],
                                    direction: others[i]['exit'] === 'left' ? 'left' : 'right',
                                    disabled: others[i]['exit'] === 'right'
                                });
                                }
                                this.list = ret;
                                     this.projectInfo = true;
                                    // this.nznot.create('success',val.msg,val.msg);
                                    // this.getData();
                                },
                                (error) => {
                                    this.nznot.create('error', error.code , error.msg);
                                }
                            );

            } else if (event.names.key  === 'association') {
                this.assbranch = undefined;
                this.branchdataInfo = false;
                this.getBranch();
                this.addBranch.branchFor = null;
                this.addBranch.branchType = null;
                this.assVisible = true;
                this.exitInfo = event;
            } else if (event.names.key  === 'putProductStatus') {
                this.modal.open({
                    title: '已投产',
                    content: '您是否确定已投产?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        this.utilityService.putData(appConfig.testUrl  + appConfig.API.sWorkitem + '/' +  event.guid + '/putProductStatus',  {} )
                            .subscribe(
                                (val) => {
                                    this.nznot.create('success', val.msg, val.msg);
                                    this.getData();
                                },
                                (error) => {
                                    this.nznot.create('error', error.code , error.msg);
                                }
                            );
                    },
                    onCancel: () => {

                    }
                });
            } else if (event.names.key  === 'close') {
                this.modal.open({
                    title: '取消关联',
                    content: '您是否确定取消关联分支?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        this.utilityService.getData(appConfig.testUrl  + appConfig.API.sWorkitem + '/' +  event.guid + '/cancel')
                            .subscribe(
                                (val) => {
                                    this.nznot.create('success', val.msg, val.msg);
                                    this.getData();
                                },
                                (error) => {
                                    this.nznot.create('error', error.code , error.msg);
                                }
                            );
                    },
                    onCancel: () => {

                    }
                });


            } else if (event.names.key  === 'branchDDetail') {
                this.utilityService.getData(appConfig.testUrl  + appConfig.API.sWorkitem + '/' + event.guid + '/branchDetail')
                    .subscribe(
                        (val) => {
                             this.branchInfo = true;
                             this.branchData = val.result;
                             this.branchData.createTime = moment(this.branchData.createTime).format('YYYY-MM-DD');
                        },
                        (error) => {
                            this.nznot.create('error', error.code , error.msg);
                        });
            } else if(event.names.key === 'revert') {
                this.getreverts = []
                this.reason = null;
                this.searchRevert = null;
                this.selectedRowslist = 0;

                this.getRevert()
            }else if(event.names.key === 'cenel'){

                this.modal.open({
                    title: '取消工作项',
                    content: '您是否确定取消工作项?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: () => {
                        this.utilityService.putData(appConfig.testUrl  + appConfig.API.sWorkitem + '/' + event.guid + '/status' ,{} )
                            .subscribe(
                                (val) => {
                                    this.nznot.create('success', val.msg , val.msg);
                                    this.getData();
                                },(error) =>{
                                    this.nznot.create('error', error.code , error.msg);
                                }
                            );
                    },
                    onCancel: () => {

                    }
                });
            }else{
                   this.getdelay()
            }
        }
    }
        isInArray(arr,value){
    for(var i = 0; i < arr.length; i++){
        if(value === arr[i]){
            return true;
        }
    }
    return false;
}

   getdelay(option?){
          if (option) {
           this.revertPageIndex =1;
        }
        const page = {
                    condition: {fullPath:this.searchRevert}, // 搜索内容
                        page: {
                            size: 10,
                            current: this.revertPageIndex
                        }
                    };
                      this.listloading = true;
            this.utilityService.postData(appConfig.testUrl  +'/sWorkitem/'+ this.workId+'/standardListAll ', page )
                .subscribe(
                    (val) => {
                                  this.listloading = false;
                                  val.result.records.forEach((i,index)=>{
                                      val.result.records[index]['index'] = index+1;
                                      i.checked = false;
                                      this.delaysSeclect.forEach(j=>{
                                          if(i.guid === j){
                                              i.checked = true;
                                          }
                                      })
                                  });
                                  this.revertListData = val.result.records
                                  this.revertpageTotal = val.result.pages * 10;
                                  this.revertListModal = true
                                //   this.delaypageTotal = val.result.pages * 10;
                                //   this.delayListModal = true
                    },(error)=>{
                        this.revertListModal = false;
        this.nznot.create('error',error.code ,error.msg );
                    })
         }

    subProject() {
        let projectGuids = []
        // this.projectInfo = false;
        for (let i = 0 ; i < this.list.length; i ++) {
                if (this.list[i].status === 'right' && this.list[i].disabled === false) {
                projectGuids.push(this.list[i].guid);
            }
        }
        this.loading = true;
          this.utilityService.postData(appConfig.testUrl  + appConfig.API.sWorkitem + '/' + this.workId + '/project' ,{projectGuids: projectGuids} )
                            .subscribe(
                                (val) => {
                                     this.loading = false;
                                    this.projectInfo = false;
                                    this.nznot.create('success', val.msg , val.msg);
                                    this.getData();
                                } ,
                            (error) => {
                              this.loading = false;
                             this.nznot.create('error', error.msg, '');
                            }
                            );
            }
    isShowArtf = false;
   artfmsg = '只能输入数字类型'
    checkArtf(event){
        let MOBILE_REGEXP =/^\+?[1-9][0-9]*$/;
        if (MOBILE_REGEXP.test(event) === true ) {
            this.isShowArtf = false
            let url = '/sWorkitem/verifyArtf';
            let obj ={
                'artf':event,
                'guidWorkitem':this.workId,
                'type':this.checkType
            };

        }else {
            this.isShowArtf = true;
              this.artfmsg = '只能输入数字类型'
        }


    }
    // 选中复选框方法
    getreverts = []
    selectId:number;
    selectedRow(event) {

            this.getreverts = []
        event.selectedRows.forEach(i=>{
               this.getreverts.push(i.guid)
        })

          let obj = []

             this.getreverts.forEach(i=>{
                let str =  this.isInArray(this.delaysSeclect,i);
                if(!str){
                 this.delaysSeclect.push(i)
                }
             })
               if(event.it && !event.it.checked){
            this.selectId = event.it.guid
               this.delaysSeclect.forEach(k=>{
                if(k!==this.selectId){
                obj.push(k)
                }
            })
              this.delaysSeclect = obj;
        }
    }
    delList(){
        this.reason = null;
           this.delaysSeclect = [];
           this.getreverts = [];
        this.revertListModal = false;
    }
    checkBranch(guid) {
        this.utilityService.getData(appConfig.testUrl  + appConfig.API.sBranchadd + '/' + guid)
            .subscribe(
                (val) => {
                  this.branchData = val.result;
                  this.branchdataInfo = true; // 默认不显示详情
                  this.branchData.createTime = moment(this.branchData.createTime).format('YYYY-MM-DD');
                }
            );
    }
    // 弹出框确定
   getArray(a) {
 var hash = {},
     len = a.length,
     result = [];

 for (var i = 0; i < len; i++){
     if (!hash[a[i]]){
         hash[a[i]] = true;
         result.push(a[i]);
     }
 }
 return result;
}

loading = false;
    save() {

        this.workAdd.receiveTime = moment(this.workAdd.receiveTime).format('YYYY-MM-DD');
        this.workAdd.developStartTime = moment(this.workAdd.developStartTime).format('YYYY-MM-DD');
        this.workAdd.deliveryTime = moment(this.workAdd.deliveryTime).format('YYYY-MM-DD');
        this.workAdd.deliveryPlanTime = moment(this.workAdd.deliveryPlanTime).format('YYYY-MM-DD');

        if (_.isArray(this.workAdd.developersAdd)) {
            let arr = []
            this.workAdd.developersAdd.forEach(i=>{
                 arr.push(i.userId)
            })
            arr = this.getArray(arr);//数组去重
            this.workAdd.developers = arr.join( ',' );
        }

        if(this.isShowArtf === true) {
            this.nznot.create('error', 'ARTF输入不合法', '请检查ARTF');
            return;
        }
         console.log(this.workAdd)
        if (!this.workAdd.itemName || !this.workAdd.developers || !this.workAdd.owner || !this.workAdd.requirementDesc || !this.workAdd.workType || !this.workAdd.artf ) {
            this.nznot.create('error', '信息不全！', '请检查信息是否完整');
            return;
        }

        if(this.isShowitemName||this.isShowseqno||this.isShowrequirementDesc){
             this.nznot.create('error', '输入不合法', '请检查信息输入是否合法');
            return;
        }
           this.loading = true;
        if (this.isEdit) { // 修改
            this.utilityService.putData(appConfig.testUrl  + appConfig.API.sWorkitem , this.workAdd )
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                           this.loading = false;
                     this.modalVisible = false;
                    },
                    error => {
                          this.loading = false;
                        this.nznot.create('error', error.code , error.msg);
                    }
                )
            ;
        } else {
            this.utilityService.postData(appConfig.testUrl  + appConfig.API.sWorkitem, this.workAdd )
                .subscribe(
                    (val) => {
                         this.loading = false;
                        console.log(val)
                        if (val.code === '200') {
                              this.loading = false;
                             this.modalVisible = false;
                              this.modal.open({
                                title: '信息提示',
                                content: val.msg + '是否需要立即关联分支？',
                                okText: '确定',
                                cancelText: '取消',
                                onOk: () => {
                                    this.workId = val.result
                                    this.addBranch.branchFor = null;
                                    this.addBranch.branchType = null;
                                    this.assVisible = true;

                                },
                                onCancel: () => {

                                }
                            });
                        }else {

                              this.nznot.create('error', val.msg , val.msg);
                        }

                        this.getData();
                    },
                    error => {
                         this.loading = false;
                        this.nznot.create('error', error.code , error.msg);
                    }
                );

        }


    }


    // 关联分支
    assSave() {
        let url = '';
        if (this.active === true) { // 选择已有分支
         if (this.assbranch === undefined){
              this.nznot.create('error', '请输入完整分支信息', '');
             return;
         }
         this.loading = true;
         this.utilityService.getData(appConfig.testUrl  + appConfig.API.sWorkitem + '/' + this.workId + '/branch/'  + this.assbranch)
            .timeout(5000)
            .subscribe(
                (val) => {
                this.loading = false;
                 this.getData();
                 this.assVisible = false;
                 this.nznot.create('success', val.msg, val.msg);
                }
                ,
                    error => {
                         this.loading = false;
                        this.nznot.create('error', error.code , error.msg);
                    }
            );
        }else {
            let id = '';
            if (this.addBranch.branchFor == null || this.addBranch.branchType == null) {
                 this.nznot.create('error', '请输入完整分支信息', '');
                 return;
            }
             if  (this.workId) {

                 id = this.workId;
             }else {
                  id = this.exitInfo.guid;
             };
              this.loading = true;
           this.utilityService.postData(appConfig.testUrl  + appConfig.API.sWorkitem + '/' + id + '/branch',  this.addBranch )
            .timeout(5000)
            .subscribe(
                (val) => {
                     this.loading = false;
                      this.assVisible = false;
                    this.getData();
                    this.nznot.create('success', val.msg, val.msg);
                }
                ,
                    error => {
                            this.loading = false;
                        this.nznot.create('error', error.code , error.msg);
                    }
            );
        }

    }
 inputVisible = false;
  inputValue = '';
  handleClose(removedTag: any): void {
    this.workAdd.itemLable = this.workAdd.itemLable .filter(tag => tag !== removedTag);
  }
   handleCloseDev(removedTag: any): void {
    this.workAdd.developersAdd = this.workAdd.developersAdd .filter(tag => tag !== removedTag);
    if(this.workAdd.developersAdd.length===0){
           this.strdevelopers = null;
    }

  }


  sliceTagName(tag: string): string {
    const isLongTag = tag.length > 20;
    return isLongTag ? `${tag.slice(0, 20)}...` : tag;
  }

  showInput(): void {
    this.inputVisible = true;
    setTimeout(() => {
        this.input.nativeElement.focus();
    }, 10);
  }

  handleInputConfirm(): void {

    if (this.inputValue) {
        this.workAdd.itemLable.push(this.inputValue);
    }
    this.inputValue = '';
    this.inputVisible = false;
  }

  moreExport(it){
      if(it.length === 0){
        this.nznot.create('error',' 请选择工作项' , '');
         return;
      }
       this.nznot.create('info',' 正在下载，请等待' , '');
      this.utilityService.downpostData(appConfig.testUrl+'/sWorkitem/standardListExcels',it )
            .subscribe(
            (val) => {
           const file = new Blob([val._body], {type: 'application/zip'});
            const a = document.createElement('a');
            a.id = 'tempId';
            document.body.appendChild(a);
            a.download = '批量标准清单.zip';
            a.href = URL.createObjectURL(file);
            a.click();
            const tempA = document.getElementById('tempId');
            if (tempA) {
            tempA.parentNode.removeChild(tempA);
             this.nznot.create('success',' 下载成功' , '');
            }
             },(error)=>{

                this.nznot.create('error', error.code , error.msg);
           })
  }
  rllbackModal = false;
        getGoRevertList(){

           if(this.delaysSeclect.length === 0 && this.getreverts.length === 0){
              this.nznot.create('error','请勾选代码' ,'');
              return
          }
          this.reason = null;
          this.rllbackModal = true;
        }

        getRevertList(){
           if(!this.reason){
              this.nznot.create('error','请填写回退理由！' ,'');
              return
          }
          let obj ={
              guidWorkitem:this.workId,
              guidStandarLists:this.delaysSeclect,
              rollbackDesc:this.reason
          }

         this.loading = true
         this.utilityService.postData(appConfig.testUrl+'/sWorkitem/rollBack',obj)
            .subscribe(
            (val) => {
               this.loading = false
               this.revertListModal = false;
               this.rllbackModal = false;
               this.nznot.create('success', val.code , val.msg);
            }
            ,(error)=>{
                  this.loading = false
                    this.rllbackModal = false;
                  this.nznot.create('error', error.code , error.msg);
            })
        }

         checkdate(event){

     var date = event;
     var year = date.getFullYear();
     var month = date.getMonth()+1;    //js从0开始取
     if(month<10){
         month = "0"+month
     }

     var date1 = date.getDate();
     if(date1<10){
         date1 = "0"+date1
     }
     var hour = date.getHours();
     var minutes = date.getMinutes();
     var second = date.getSeconds();
     this.searchFun.deliveryPlanTime = year+"-"+month+"-"+date1

}


}
